<?php
namespace app\admin\controller;

use think\Loader;
use think\Request;
use app\common\controller\Base;
use app\common\model\CaseCat as CaseCatModel;
use app\common\tool\Tool;


/**
 * Class CaseCat
 * @package app\admin\controller
 */
class CaseCat extends Base
{
    public function index(){

        $caseCats = CaseCatModel::all();

        $caseCatsById = collection($caseCats)->toArray();
        $caseCatsById = Tool::changeArrayKey($caseCatsById);
        return view('',['caseCats'=>$caseCats,'caseCatsById'=>$caseCatsById]);
    }


    public function add(){
        $caseCats = CaseCatModel::where('pid',0)->select();

        return view('',['caseCats'=>$caseCats]);
    }


    public function create(Request $request){

        $data = $request ->only(['name','pid']);

        $validate = Loader::validate('CaseCatValidate');
        $result = $validate ->scene('add')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }

        $caseCatModel = new CaseCatModel();
        $caseCatModel -> save($data);

        $this->success("添加成功");
    }


    public function edit(Request $request){
        $id = $request->param('id');

        $caseCat = CaseCatModel::find($id);
        $caseCats = CaseCatModel::where('pid',0)->select();

        return view('',['caseCat'=>$caseCat,'caseCats'=>$caseCats]);
    }

    public function update(Request $request){
        $data = $request->only(['name','pid']);
        $id = $request -> param('id');
        if(!$id){
            $this->error('非法来源');
        }

        if($data['pid'] == $id){
            $this->error('不能选择自己');
        }

        $validate = Loader::validate('CaseCatValidate');
        $validate -> scene('edit')->check($data);

        $caseCatModel = CaseCatModel::find($id);
        $caseCatModel -> save($data);

        $this->success('更新成功');
    }


    public function delete(Request $request){
        $id = $request -> param('id');
        CaseCatModel::destroy($id);
        $this->success("删除成功");
    }

    public function seo(Request $request){
        $id = $request->param('id',0,'intval');
        $data = CaseCatModel::find($id);
        if(!$data){
            $this->error("来源渠道非法");
        }

        return view('',['data'=>$data]);
    }

    public function seoUpdate(Request $request){
        if(!$request->isPost()){
            $this->error("非法途径访问");
        }

        $data = $request->only(['seo_title','seo_keywords','seo_description']);
        $id = $request->param('id',0,'intval');
        $model = CaseCatModel::find($id);
        if(!$model){
            $this->error("非法途径访问");
        }

        $model->save($data);
        $this->success("操作成功");
    }
}

